#include <WaitQueueEvent.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <csp_protocol_msg.h>



WaitQueueEvent::WaitQueueEvent(int process_count_, ProcessComposition *pc)
{
	process_count = process_count_;
	waitingProcess = pc;
	is_active = 0;
	acc_status = 0;

	if( pthread_mutex_init(&mutex, NULL) || pthread_cond_init(&condition, NULL) ){
		perror("Could not initialize wait-process event.");
		exit(-1);
	}
}

WaitQueueEvent::~WaitQueueEvent()
{}


void 
WaitQueueEvent::Trigger(int exit_status)
{
	pthread_mutex_lock(&mutex);
	if( !is_active ){
		//printf("WaitEvent: waiting for condition\n");
		pthread_cond_wait(&condition, &mutex);
		//printf("WaitEvent: recieved signal!\n");
	}
	//printf("WaitEvent: countdown\n");
	process_count--;
	if( exit_status ){
		acc_status = exit_status;	
	}
	if( !process_count ){
		//printf("WaitEvent: scheduled!\n");
		waitingProcess->SetState(STATE_YIELD);
		waitingProcess->SetExitStatus(acc_status);
		waitingProcess->Schedule();
		//printf("Hej!\n");
	}
	pthread_mutex_unlock(&mutex);
}

void
WaitQueueEvent::SetActive()
{
	pthread_mutex_lock(&mutex);
	is_active = 1;
	//printf("WaitEvent: about to signal\n");
	pthread_cond_signal(&condition);
	//printf("WaitEvent: signal!\n");
	pthread_mutex_unlock(&mutex);
}

